<template>
  <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
    <el-tab-pane label="待审核" name="first">
      <el-form :inline="true" :model="state.dataForm" @keyup.enter="state.getDataList()" style="margin-top: 10px">
        <div class="grid-container">
          <el-form-item label="公司名称">
            <el-input v-model="state.dataForm.companyName" type="text" clearable placeholder="请输入公司名称"
              @change="queryData"></el-input>
          </el-form-item>
        </div>
        <el-table :header-cell-style="{ background: '#eef1f6', color: '#1f2d3d', 'border-color': '#dfe6ec' }"
          v-loading="state.dataListLoading" :data="state.dataList" border
          @selection-change="state.dataListSelectionChangeHandle" style="width: 100%">
          <el-table-column align="center" prop="certifiedId" label="认证编号" width="180"
            show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="companyName" label="公司名称" width="200"
            show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="createdAt" label="认证申请时间" width="180"
            show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="auditName" label="审核人" width="100"
            show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="auditTime" label="审核时间" width="180"
            show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="auditStatus" label="审核状态" width="100">
            <template v-slot="scope">
              <span v-if="scope.row.auditStatus === '0'">待审核</span>
              <span v-else-if="scope.row.auditStatus === '1'">已通过</span>
              <span v-else-if="scope.row.auditStatus === '2'">已驳回</span>
              <span v-else-if="scope.row.auditStatus === '3'">未审核</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="驳回原因" show-overflow-tooltip>
            <template v-slot="scope">
              <span v-if="scope.row.auditStatus !== '1'">{{ scope.row.auditReason || "--" }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" align="center" label="操作" width="200">
            <template v-slot="scope">
              <!-- 已通过/驳回：只读查看 -->
              <el-button link style="color: rgba(22, 119, 255, 1)" @click="ToView(scope.row)">
                查看
              </el-button>
              <!-- 待审核：进入流程页，并带上 auditMode=1 -->
              <el-button v-if="scope.row.auditStatus === '0'" link style="color: rgba(22, 119, 255, 1)"
                @click="ToAudit(scope.row)">
                审核
              </el-button>


            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <el-pagination :current-page="state.page" :page-sizes="[10, 20, 50, 100]" :page-size="state.limit"
        :total="state.total" layout="total, sizes, prev, pager, next, jumper" @size-change="state.pageSizeChangeHandle"
        @current-change="state.pageCurrentChangeHandle"> </el-pagination>
      <!-- 审核弹窗 -->
      <AuditDialog ref="auditDialogRef" @success="state.getDataList()" />
    </el-tab-pane>
    <el-tab-pane label="全部" name="second">
      <el-form :inline="true" :model="state.dataForm" @keyup.enter="state.getDataList()" style="margin-top: 10px">
        <div class="grid-container">
          <el-form-item label="公司名称">
            <el-input v-model="state.dataForm.companyName" type="text" clearable placeholder="请输入公司名称"
              @change="queryData"></el-input>
          </el-form-item>

          <el-form-item label="审核状态">
            <el-select v-model="state.dataForm.auditStatus" placeholder="请选择审核状态" clearable @change="queryData">
              <el-option label="待审核" value="0"></el-option>
              <el-option label="审核通过" value="1"></el-option>
              <el-option label="审核驳回" value="2"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-table :header-cell-style="{ background: '#eef1f6', color: '#1f2d3d', 'border-color': '#dfe6ec' }"
          v-loading="state.dataListLoading" :data="state.dataList" border
          @selection-change="state.dataListSelectionChangeHandle" style="width: 100%">
          <el-table-column align="center" prop="certifiedId" label="认证编号" width="180"
            show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="companyName" label="公司名称" width="200"
            show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="createdAt" label="认证时间" width="180"
            show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="auditName" label="审核人" width="100"
            show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="auditTime" label="审核时间" width="180"
            show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="auditStatus" label="审核状态" width="100">
            <template v-slot="scope">
              <span v-if="scope.row.auditStatus === '0'">待审核</span>
              <span v-else-if="scope.row.auditStatus === '1'">已通过</span>
              <span v-else-if="scope.row.auditStatus === '2'">已驳回</span>
              <span v-else-if="scope.row.auditStatus === '3'">未审核</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="驳回原因" show-overflow-tooltip>
            <template v-slot="scope">
              <span v-if="scope.row.auditStatus !== '1'">{{ scope.row.auditReason || "--" }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" align="center" label="操作" width="200">
            <template v-slot="scope">
              <!-- 已通过/驳回：只读查看 -->
              <el-button link style="color: rgba(22, 119, 255, 1)" @click="ToView(scope.row)">
                <!-- router.replace({
                  path: '/cnas/certification-process',
                  query: { id: scope.row.id, viewOnly: '1' }
                }) -->

                查看
              </el-button>
              <!-- 待审核：进入流程页，并带上 auditMode=1 -->
              <el-button v-if="scope.row.auditStatus === '0'" link style="color: rgba(22, 119, 255, 1)"
                @click="ToAudit(scope.row)">
                审核
              </el-button>


            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <el-pagination :current-page="state.page" :page-sizes="[10, 20, 50, 100]" :page-size="state.limit"
        :total="state.total" layout="total, sizes, prev, pager, next, jumper" @size-change="state.pageSizeChangeHandle"
        @current-change="state.pageCurrentChangeHandle"> </el-pagination>
      <!-- 审核弹窗 -->
      <AuditDialog ref="auditDialogRef" @success="state.getDataList()" />
    </el-tab-pane>
  </el-tabs>


</template>
<script lang="ts" setup>
import baseService from "@/service/baseService";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import useView from "@/hooks/useView";
import { nextTick, reactive, ref, toRefs, onMounted, onUnmounted } from "vue";
import router from "@/router";
import AuditDialog from "@/components/AuditDialog.vue";
import tabBus from "@/utils/tabBus";

import type { TabsPaneContext } from 'element-plus'

const ToAudit = (row: any) => {
  router.replace({
    path: '/cnas/certification-process',
    query: { id: row.id, viewOnly: '1', auditMode: '1' }
  })
}

const ToView = (row: any) => {
  router.replace({
    path: '/cnas/certification-process',
    query: { id: row.id, viewOnly: '1' }
  })
}

const activeName = ref('first')

const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event)
  // 根据标签页切换设置不同的查询条件
  if (tab.props.name === 'first') {
    // 待审核标签页：只显示待审核数据
    state.dataForm.auditStatus = "0";
  } else if (tab.props.name === 'second') {
    // 全部标签页：清除审核状态筛选
    state.dataForm.auditStatus = "";
  }
  // 重置页码并重新获取数据
  state.page = 1;
  state.getDataList();
}

const view = reactive({
  getDataListURL: "/noc/authcompanyaudit/list",
  getDataListIsPage: true,
  dataForm: {
    companyName: "",
    auditStatus: ""
  }
});
// 分类选项
const classOptions = ref<any[]>([]);
// 选中的分类路径
const selectedClassPath = ref<string[]>([]);
// 状态多选值
const selectedStatus = ref([]);
const auditDialogRef = ref<InstanceType<typeof AuditDialog>>();
const auditHandle = (row: any) => {
  auditDialogRef.value?.open(row);
};

// 修改查询按钮的点击处理
const queryData = () => {
  saveCurrentQuery();
  // 如果当前在"待审核"标签页，确保审核状态为"0"
  if (activeName.value === 'first') {
    state.dataForm.auditStatus = "0";
  }
  state.page = 1; // 重置页码到第一页
  state.getDataList();
};

// 修改重置方法以清除保存的查询条件
const resetForm = () => {
  view.dataForm.companyName = "";
  // 根据当前标签页设置审核状态
  if (activeName.value === 'first') {
    view.dataForm.auditStatus = "0";
  } else {
    view.dataForm.auditStatus = "";
  }
  state.page = 1; // 重置页码到第一页
  state.getDataList();
};

// 在执行查询前保存当前查询条件
const saveCurrentQuery = () => {
  const query = {
    dataForm: { ...state.dataForm },
    selectedStatus: [...selectedStatus.value],
    selectedClassPath: [...selectedClassPath.value]
  };
  sessionStorage.setItem("nocproductListQuery", JSON.stringify(query));
};
// 在 onMounted 中添加
onMounted(() => {
  // 初始化时设置待审核状态（因为默认是第一个标签页）
  state.dataForm.auditStatus = "0";
  state.getDataList();
  tabBus.on("refreshCompanyList", state.getDataList);
});
onUnmounted(() => {
  tabBus.off("refreshCompanyList", state.getDataList);
});
const state = reactive({ ...useView(view), ...toRefs(view) });
state.limit = 20;
</script>
<style lang="scss" scoped>
::v-deep .el-table .cell {
  white-space: nowrap;
}

.el-input {
  width: 218px;
  height: 32px;
  opacity: 1;
  border-radius: 5px;
  background: rgba(255, 255, 255, 1);
}

.form {
  display: flex;
  justify-content: space-between;
}

.grid-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: left;
  // grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  /* 自动适应列宽，每列至少200px */
  gap: 16px;
  /* 元素间距 */
}

.demo-tabs>.el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
</style>
